<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/11/5
 * Time: 14:07
 */

namespace app\Service;


use app\api\model\Coupon\CouponModel;
use app\api\model\Course\CourseModel;
use app\api\model\Goods\GoodsModel;
use app\api\model\Index\VideoUser;
use app\api\model\Order\OrderModel;
use app\api\model\Sns\Sns;
use app\api\model\Sns\SnsModel;
use app\api\model\System\SysSettingModel;
use app\api\model\User\UserModel;
use app\api\model\Video\VideoModel;
use app\api\model\Video\VideoUserRelationModel;
use app\api\model\VideoUser\VideoUserModel;
use app\Utils\ImageUtil;
use think\facade\Db;

class UserService extends BaseService
{
    protected $table;

    public function __construct()
    {
        $this->table = new SnsModel();
    }

    public function userCenter(int $user_id, $user)
    {
        $like = VideoUser::where(['user_id' => $user_id, 'is_show' => 1])->sum('nums_like');
        //关注
        $fallow = SnsModel::where('sns_frommid', $user_id)->count();
        //粉丝
        $fans = SnsModel::where('sns_tomid', $user_id)->count();
        $where = [
            ['user_id', '=', $user_id],
            ['is_show', '=', 1],

        ];
        //作品数 动态数， 视频
        $self = VideoUserModel::where($where)->count();
        $where[] = ['label', '<>', ''];
        $labels = VideoUserModel::where($where)->field('label')->group('label')->select()->toArray();
        if (count($labels) > 0) {
            $labels = array_column($labels, 'label');
        }
        $result = [
            'head_img' => $user['head_img'],
            'nickname' => $user['nickname'],
            'usn' => $user['sn'],
            'city' => $user['city'],
            'like' => $like,
            'fallow' => $fallow,
            'fans' => $fans,
            'self' => $self,
            'labels' => $labels,
            'identity' => $user['identity'], //是否老师
            'introduce' => $user['introduce'], //介绍
        ];
        return $result;
    }

    /**
     * 关注列表
     */
    public function follow(int $user_id, int $page, int $limit)
    {
        $offset = ($page - 1) * $limit;
        $list = $this->table->with('user')->field('sns_addtime,sns_tomid')
            ->where('sns_frommid', $user_id)
            ->limit($offset, $limit)
            ->select();
        $count = $list->count();
        return compact('count', 'list');
    }

    /**
     * 粉丝列表
     */
    public function fans(int $user_id, int $page, int $limit)
    {
        $offset = ($page - 1) * $limit;
        $list = Sns::with('user')->field('sns_addtime,sns_frommid')
            ->where('sns_tomid', $user_id)
            ->limit($offset, $limit)
            ->select();
        $count = $list->count();
        return compact('count', 'list');
    }

    /**
     * 老师商品列表
     */
    public function goods_lists(int $user_id, string $good_name, int $cate_id, int $is_recommend, $is_bargain, $is_composite, $is_price, $is_sales, int $page, int $limit)
    {
        $where = [
            ['is_show', '=', 1],
            ['is_del', '=', 0]
        ];
        $offset = ($page - 1) * $limit;
        $merchant = Db::name('merchant')->where('user_id', '=', $user_id)->find();
        if (!$merchant) return false;
        $list = Db::name('goods')->with('cate_relation')
            ->field('id,good_name,label,img,slider_img,brief,price,vip_price,group_price,group_num,is_postage,postage,is_hot,is_new,is_benefit,is_recommend,sales,ficti,browse')
            ->when($good_name, function ($query) use ($good_name) {
                return $query->where('good_name', 'like', '%' . $good_name . '%');
            })
            ->when($is_recommend, function ($query) use ($is_recommend) {
                return $query->where('is_recommend', '=', $is_recommend);
            })
            ->when($is_bargain, function ($query) use ($is_bargain) {
                return $query->where('is_bargain', '=', $is_bargain);
            })
            ->when($cate_id, function ($query) use ($cate_id) {
                return $query->whereHas('cate_relation', function ($query) use ($cate_id) {
                    return $query->where('cate_id', '=', $cate_id);   //分类ID
                });
            })
            ->where($where)
            ->limit($offset, $limit)
            ->order(['id' => 'desc'])
            ->where('mer_id', '=', $merchant['id'])
            ->select();
        return ['data' => $this->goods_lists_serialize($list), 'count' => $list ? $list->count() : 0];
    }

    /**
     * 数据序列化
     */
    public function goods_lists_serialize($list)
    {
        $arr = [];
        foreach ($list as $key => $item) {
            $images = !empty($item['slider_img']) ? json_decode($item['slider_img'], true) : [];
            foreach ($images as &$image) {
                $image = ImageUtil::i()->replaceUrl($image);
            }
            $item['slider_img'] = $images;
            $item['label'] = is_array($item['label']) ? $item['label'] : json_decode($item['label'], true);
            $arr[] = $item;
        }
        return $arr;
    }

    /**
     * 老师课程列表
     */
    public function curriculum_lists(int $user_id, array $param)
    {
        $merchant = Db::name('merchant')->where('user_id', '=', $user_id)->find();
        if (!$merchant) return false;
        $where = [
            ['c.is_show', '=', 1],
            ['c.is_del', '=', 0],
            ['c.mer_id', '=', $merchant['id']]
        ];
        $page = !empty($param['page']) ? $param['page'] : 1;
        $limit = !empty($param['limit']) ? $param['limit'] : 10;
        $title = !empty($param['title']) ? $param['title'] : "";
        $cate_id = isset($param['cate_id']) ? $param['cate_id'] : "";
        $school_id = !empty($param['school_id']) ? $param['school_id'] : 0;
        $area_id = !empty($param['area_id']) ? $param['area_id'] : 0;
        if (!empty($title)) {
            array_push($where, ['c.title', 'like', '%' . $title . '%']);
        }
        if (!empty($school_id)) {
            array_push($where, ['c.school_id', '=', $school_id]);
        }
        if (!empty($area_id)) {
            array_push($where, ['s.area_id', '=', $area_id]);
        }
        if (isset($cate_id)) {
            if ($cate_id == 0) {
             //   array_push($where, ['c.is_recommend', '=', 1]);
            } else {
                array_push($where, ['ccr.cate_id', '=', $cate_id]);
            }
        }
        $list = CourseModel::getCourseListWhere($page, $limit, $where, "c.id,c.title,c.mer_id,c.img,c.teacher_brief,c.brief,c.price,c.group_price,c.is_group,c.group_num,c.cost_price,c.vip_price,c.school_id,c.start_time,c.end_time,sa.area_name,cc.cate_name");
        $count = CourseModel::getCourseCountWhere($where);
        foreach ($list as &$item) {
            $item['img'] = ImageUtil::i()->replaceUrl($item['img']);
            /*$images = !empty($item['slider_img']) ? json_decode($item['slider_img'],true) : [];
            foreach ($images as &$image){
                $image = ImageUtil::i()->replaceUrl($image);
            }
            $item['slider_img'] = $images;
            $item['details'] = !empty($item['details']) ? htmlspecialchars_decode($item['details']) : "";*/

            //相关优惠券
            $cou_where = [
                ['label', '=', 1],
                ['is_show', '=', 1],
                ['goods_ids', 'like', '%' . $item['id'] . ',' . '%'],
                ['start_time', '<', date("Y-m-d H:i:s", time())],
                ['end_time', '>', date("Y-m-d H:i:s", time())]
            ];
            $cou_where_1 = [
                ['label', '=', 1],
                ['is_show', '=', 1],
                ['type', '=', 1],
                ['start_time', '<', date("Y-m-d H:i:s", time())],
                ['end_time', '>', date("Y-m-d H:i:s", time())]
            ];
            $coupon_list = CouponModel::getCouponWhereOrMore([$cou_where, $cou_where_1], "id,coupon_title,is_level,label,attr,type,amount,total_amount");
            $item['coupon_list'] = !empty($coupon_list) ? $coupon_list : [];

            //总报名人数
            $or_where = [
                ['o.type', '=', 3],
                ['og.type', '=', 3],
                ['o.status', '<>', 4],
                ['o.status', '<>', -1],
                ['og.goods_id', '=', $item['id']],
                ['o.add_time', '>=', $item['start_time']],
                ['o.add_time', '<=', $item['end_time']],
            ];
            $item['course_all_count'] = count(OrderModel::getOrderWhereJoinMore($or_where));
        }
        return compact('list', 'count');
    }

    /**
     * 老师入驻申请联系信息
     */
    public function teacher()
    {
        $info = SysSettingModel::field('phone,wx_number,teacher_text')->order('id desc')->find();
        $info['wx_number'] = explode(',', $info['wx_number']);
        $info['phone'] = explode(',', $info['phone']);
        return $info;
    }

    /**
     * 老师线上课程
     */
    public function teacher_courses(array $user)
    {
        $list = VideoUserRelationModel::where('user_id', $user['id'])->field('video_id')->with(['video' => function ($query) {
            return $query->field('id,video_title');
        }])->select();
        return $list;
    }


    /**
     * @param array $param
     * @param $uid
     * @return array
     * 老师线上课程列表
     */
    public function teacher_courses_list(array $param, $uid)
    {
        $where = [
            ['v.is_show', '=', 1]
        ];
        $page = !empty($param['page']) ? $param['page'] : 1;
        $limit = !empty($param['limit']) ? $param['limit'] : 10;
        $video_title = !empty($param['video_title']) ? $param['video_title'] : "";
        $cate_id = isset($param['cate_id']) ? $param['cate_id'] : "";
        if (!empty($video_title)) {
            array_push($where, ['v.video_title', 'like', '%' . $video_title . '%']);
        }
        if (isset($cate_id)) {
            if ($cate_id == 0) {
                array_push($where, ['v.is_recommend', '=', 1]);
            } else {
                array_push($where, ['vcr.cate_id', '=', $cate_id]);
            }
        }
        $list = VideoModel::getVideoListWheres($page, $limit, $uid, $where);
        $count = VideoModel::getVideoCountWheres($where, $uid);
        foreach ($list as &$item) {
            $item['label'] = !empty($item['label']) ? json_decode($item['label'], true) : [];
            $item['img'] = ImageUtil::i()->replaceUrl($item['img']);
            $images = !empty($item['slider_img']) ? json_decode($item['slider_img'], true) : [];
            foreach ($images as &$image) {
                $image = ImageUtil::i()->replaceUrl($image);
            }
            $item['slider_img'] = $images;
            $item['details'] = !empty($item['details']) ? htmlspecialchars_decode($item['details']) : "";
        }
        return compact('list', 'count');
    }
}